let router = require('../router/Router');

let sysService = require('../service/sysUserService');
let exchangeService = require('../service/exchangeService');
let noticeService = require('../service/noticeService');
let userService = require('../service/userService');
let pcService = require('../service/countryPhoneCodeService');
let cmService = require('../service/cmService');
let gameService = require('../service/gameService');
let questionService = require('../service/questionService');
let payOrderService = require('../service/PayOrderService');

const { BusiError, SysError, ErrorResult } = require('../exception/exception');

router.post('/admin/country/phonecode', function (req, resp) {
    console.log(req.body.ip);
    if (!req.body.ip) {
        resp.end(JSON.stringify({code: 500, msg: 'invalid ip'}));
        return;
    }

    pcService.getCountryCodeByIp(req.body.ip).then(res => {
        resp.end(JSON.stringify({code: 200, msg: 'success', data: res}));
    }).catch(e => {
        console.log("get country phone code err:", e);
        resp.end(JSON.stringify({code: 500, msg: 'get country phone code err'}));
    });
});

router.post('/admin/buffer/update', (req, resp) => {
    if(!req.body.uid || req.body.uid === ""){
        resp.end(JSON.stringify({code: 500, msg: 'uid不能为空'}));
        return;
    }

    if(!req.body.buffer || req.body.buffer === 0){
        resp.end(JSON.stringify({code: 500, msg: 'buffer不能等于0'}));
        return;
    }

    userService.updateBuffer(req.body.uid, req.body.buffer, req.operator, req.body.flag).then(res => {
        resp.end(JSON.stringify({code: 200, msg: 'success', data: res}));
    }).catch(err => {
        console.log("/admin/buffer/update err:", err);
        resp.send(new ErrorResult(err));
    });
});

router.post('/admin/flag/update', (req, resp) => {
    if(!req.body.uid || req.body.uid === ""){
        resp.end(JSON.stringify({code: 500, msg: 'uid不能为空'}));
        return;
    }

    if(req.body.flag < 0){
        resp.end(JSON.stringify({code: 500, msg: 'flag不能<0'}));
        return;
    }

    userService.updateFlag(req.body.uid, req.body.flag, req.operator).then(res => {
        resp.end(JSON.stringify({code: 200, msg: 'success', data: res}));
    }).catch(err => {
        console.log("/admin/flag/update err:", err);
        resp.send(new ErrorResult(err));
    });
});

/**
 *      username {String}
 *      password {String}
 */
router.post('/admin/login', function (req, resp) {
    if (!req.body.username){
        resp.send({code: 500, msg: "username invalid"});
        return;
    }

    if (!req.body.password){
        resp.send({code: 500, msg: "password invalid"});
        return;
    }

    sysService.validSysUser(req.body.username, req.body.password).then(res => {
        if (res) {
            resp.send({code: 200, msg: "success", token: res});
        }else{
            resp.send({code: 500, msg: "登录失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * @param cond
 *      cond.uid
 *      cond.name
 *      cond.phone
 *      cond.startTime
 *      cond.endTime
 */
router.post('/admin/auth/users/query', function (req, resp) {
    let cond = {};
    if (req.body.uid){
        cond.uid = req.body.uid;
    }

    if (req.body.startTime){
        cond.startTime = req.body.startTime;
    }

    if (req.body.endTime){
        cond.endTime = req.body.endTime;
    }

    if (req.body.name){
        cond.name = req.body.name;
    }

    if (req.body.phone){
        cond.phone = req.body.phone;
    }

    if (req.body.page) {
        cond.page = req.body.page;
    }

    if (req.body.count){
        cond.count = req.body.count;
    }

    userService.queryPage(cond).then(res => {
        if (res){
            resp.send({code: 200, msg: "success", data: res});
        } else{
            resp.send({code: 500, msg: "查询失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * @param
 *      cond.flowNo
 *      cond.uid
 *      cond.status
 *      cond.type
 *      cond.startTime
 *      cond.endTime
 *      cond.page
 *      cond.count
 */
router.post('/admin/auth/finance/recharge/query', function (req, resp) {
    resp.send({code: 500, msg: "暂无"});
});

/**
 *  提现查询
 *  @param
 *      cond.uid
 *      cond.flowNo
 *      cond.status
 *      cond.type
 *      cond.startTime
 *      cond.endTime
 *      cond.page
 *      cond.count
 */
router.post('/admin/auth/finance/withdraw/query', function (req, resp) {
    let cond = {};
    if (req.body.uid){
        cond.uid = req.body.uid;
    }

    if (req.body.status){
        cond.status = req.body.status;
    }

    if (req.body.flowNo){
        cond.flowNo = req.body.flowNo;
    }

    if (req.body.type) {
        cond.type = req.body.type;
    }

    if (req.body.startTime){
        cond.startTime = req.body.startTime;
    }

    if (req.body.endTime){
        cond.endTime = req.body.endTime;
    }

    if (req.body.page) {
        cond.page = req.body.page;
    }

    if (req.body.count){
        cond.count = req.body.count;
    }
    exchangeService.queryPageByCond(cond).then(res => {
        if (res){
            resp.send({code: 200, msg: "success", data: res});
        } else{
            resp.send({code: 500, msg: "查询失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 确定提现
 *      flowNo {String}
 */
router.post('/admin/auth/finance/withdraw/accept', function (req, resp) {
    if (!req.body.flowNo){
        resp.send({code: 500, msg: "订单号无效"});
        return;
    }

    exchangeService.auditAccept({flowNo:req.body.flowNo, operator: req.body.username, payChannel: "J005"}).then(res => {
        if (res > 0){
            resp.send({code: 200, msg: "success"});
        } else{
            resp.send({code: 500, msg: "操作失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 拒绝提现
 *      flowNo {String}
 *      remark {String}
 */
router.post('/admin/auth/finance/withdraw/refuse', function (req, resp) {
    if (!req.body.flowNo){
        resp.send({code: 500, msg: "订单号无效"});
        return;
    }

    if (!req.body.remark){
        resp.send({code: 500, msg: "拒绝原因不能为空"});
        return;
    }

    exchangeService.auditRefuse({flowNo:req.body.flowNo, operator: req.body.username, remark: req.body.remark}).then(res => {
        if (res > 0){
            resp.send({code: 200, msg: "success"});
        } else{
            resp.send({code: 500, msg: "操作失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 公告查询
 * @param
 *      page
 *      author
 *      isTop
 */
router.post('/admin/auth/notice/query', function (req, resp) {
    if (!req.body.page){
        resp.send({code: 500, msg: "page无效"});
        return;
    }

    let cond = {};
    cond.page = req.body.page;
    if (req.body.author){
        cond.author = req.body.author;
    }

    if (req.body.isTop){
        cond.isTop = req.body.isTop;
    }

    if (req.body.startTime){
        cond.startTime = req.body.startTime;
    }

    if (req.body.endTime){
        cond.endTime = req.body.endTime;
    }

    noticeService.querySysPage(cond).then(res => {
        if (res){
            resp.send({code: 200, msg: "success", data: res});
        } else{
            resp.send({code: 500, msg: "查询失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 发布公告
 *  @param
 *      notice.title
 *      notice.content
 *      notice.category
 *      notice.isTop
 */
router.post('/admin/auth/notice/publish', function (req, resp) {
    let notice = {};
    if (!req.body.title) {
        resp.send({code: 500, msg: "标题不能为空"});
        return;
    }

    if (!req.body.content) {
        resp.send({code: 500, msg: "内容不能为空"});
        return;
    }

    if (req.body.isTop === null || req.body.isTop === undefined) {
        resp.send({code: 500, msg: "是否置顶不能为空"});
        return;
    }

    notice.title = req.body.title;
    notice.author = -1;
    notice.authorName = req.body.username;
    notice.content = req.body.content;
    notice.category = 0;
    notice.isTop = req.body.isTop;
    notice.toUid  = -1;
    noticeService.publish(notice).then(res => {
        if (res > 0){
            resp.send({code: 200, msg: "success"});
        } else{
            resp.send({code: 500, msg: "操作失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 设置置顶
 * @param
 *      id
 */
router.post('/admin/auth/notice/settop', function (req, resp) {
    if (!req.body.id){
        resp.send({code: 500, msg: "invalid id"});
        return;
    }
    noticeService.setTop(req.body.id).then(res => {
        if (res > 0){
            resp.send({code: 200, msg: "success"});
        } else{
            resp.send({code: 500, msg: "操作失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 取消置顶
 * @param
 *      id
 */
router.post('/admin/auth/notice/distop', function (req, resp) {
    if (!req.body.id){
        resp.send({code: 500, msg: "invalid id"});
        return;
    }
    noticeService.disableTop(req.body.id).then(res => {
        if (res > 0){
            resp.send({code: 200, msg: "success"});
        } else{
            resp.send({code: 500, msg: "操作失败"});
        }
    }).catch(e => {
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

/**
 * 将用户设置为代理用户
 */
router.post('/admin/auth/addRoot', (req, resp) => {
    if (!req.body.acctId){
        resp.send({code: 500, msg: "操作失败, 申请账号不能为空"});
        return;
    }

    cmService.addRoot({acctId: req.body.acctId}).then(res => {
        resp.send({code: 200, msg: "success"});
    }).catch(err => {
        resp.send({code: 500, msg: "系统异常:" + err});
    });
});

/**
 * 代理添加子用户
 */
router.post('/admin/auth/addChild', (req, resp) => {
    if (!req.body.acctId){
        resp.send({code: 500, msg: "操作失败, 申请账号不能为空"});
        return;
    }

    if (!req.body.pAcctId){
        resp.send({code: 500, msg: "操作失败, 申请父级账号不能为空"});
        return;
    }

    cmService.addChild({acctId: req.body.acctId, pAcctId: req.body.pAcctId}).then(res => {
        resp.send({code: 200, msg: "success"});
    }).catch(err => {
        resp.send({code: 500, msg: "系统异常:" + err});
    });
});

router.post('/admin/auth/users/coin/list', (req, resp) => {
    userService.getCoinAlterList(req.body).then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        let msg = "系统异常, 请稍后再试";
        if (err instanceof BusiError){
            msg = err.message;
        }
        resp.send({code: 500, msg: msg});
    });
});

/**
 * 用户增加金币
 */
router.post('/admin/auth/users/incCoin', (req, resp) => {
    if (!req.body.acctId){
        resp.send({code: 500, msg: "操作失败, 账号不能为空"});
        return;
    }

    if (!req.body.remark || req.body.remark === ''){
        resp.send({code: 500, msg: "备注不能为空"});
        return;
    }

    if (!req.body.amt){
        resp.send({code: 500, msg: "操作失败, 金额不能为空"});
        return;
    }

    let amt = Math.floor(req.body.amt).toFixed(2);
    if (amt <= 0) {
        resp.send({code: 500, msg: "操作失败, 金额有误"});
        return;
    }

    userService.updateCoin(req.body.acctId, amt, "system", req.body.remark, req.username).then(res => {
        resp.send({code: 200, msg: "success"});
    }).catch(err => {
        let msg = "系统异常, 请稍后再试";
        if (err instanceof BusiError){
            msg = err.message;
        }
        resp.send({code: 500, msg: msg});
    });
});

/**
 * 用户减少金币
 */
router.post('/admin/auth/users/decCoin', (req, resp) => {
    if (!req.body.acctId){
        resp.send({code: 500, msg: "操作失败, 账号不能为空"});
        return;
    }

    if (!req.body.remark || req.body.remark === ''){
        resp.send({code: 500, msg: "备注不能为空"});
        return;
    }

    if (!req.body.amt){
        resp.send({code: 500, msg: "操作失败, 金额不能为空"});
        return;
    }

    let amt = Math.floor(req.body.amt).toFixed(2);
    if (amt <= 0) {
        resp.send({code: 500, msg: "操作失败, 金额有误"});
        return;
    }

    userService.updateCoin(req.body.acctId, -amt, "sys_admin", req.body.remark, req.username).then(res => {
        resp.send({code: 200, msg: "success"});
    }).catch(err => {
        let msg = "系统异常, 请稍后再试";
        if (err instanceof BusiError){
            msg = err.message;
        }
        resp.send({code: 500, msg: msg});
    });
});

router.post('/admin/auth/game/active', (req, resp) => {
//hset gameHost "ws://106.14.200.66:7081/game" "{\"active\": 1,\"gameType\": \"niuniu\"}"
    if (!req.body.gameType || req.body.gameType === ""){
        resp.send({code: 500, msg: "操作失败, 游戏类型不能为空"});
        return;
    }

    if (!req.body.wsUrl || req.body.wsUrl === ""){
        resp.send({code: 500, msg: "操作失败, 游戏host不能为空"});
        return;
    }

    gameService.setGameInfo(req.body.wsUrl, {gameType: req.body.gameType, active: 1}).then(res => {
        resp.send({code: 200, msg: "success"});
    }).catch(err => {
        resp.send({code: 500, msg: "系统异常:" + err});
    });
});

router.post('/admin/auth/game/info', (req, resp) => {
//hset gameHost "ws://106.14.200.66:7081/game" "{\"active\": 1,\"gameType\": \"niuniu\"}"
    if (!req.body.gameType || req.body.gameType === ""){
        resp.send({code: 500, msg: "操作失败, 游戏类型不能为空"});
        return;
    }

    gameService.getGameInfo(req.body.gameType).then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        resp.send({code: 500, msg: "系统异常:" + err});
    });
});

router.post('/admin/auth/question/query', function (req, resp) {
    questionService.queryQuestion({page: req.body.page,
        uid: req.body.uid, startTime: req.body.startTime,
        endTime: req.body.endTime, status: req.body.status}).then(res => {

        resp.send({code: 200, msg: "success", data: res});
    }).catch(e => {
        console.logw("系统业务异常:", e);
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});


router.post('/admin/auth/question/answer', function (req, resp) {
    if (!req.body.id){
        resp.send({code: 500, msg: "提交id不能为空"});
        return;
    }

    if (!req.body.answer || req.body.answer === ""){
        resp.send({code: 500, msg: "回答内容不能为空"});
        return;
    }

    questionService.answerQuestion({id: req.body.id, answer: req.body.answer}).then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(e => {
        console.logw("系统业务异常:", e);
        resp.send({code: 500, msg: "系统异常:" + e});
    });
});

router.post("/admin/auth/user/online/cnt", (req, resp) => {
    // cacheKey
    if (!req.body.gt) {
        resp.send({code: 500, msg: "game type is null"});
        return;
    }

    gameService.getOnlineUserCnt(req.body.gt).then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        console.logw("getOnlineUserCnt err:", err.message);
        let msg = "系统异常, 请稍后再试";
        if (err instanceof BusiError){
            msg = err.message;
        }

        resp.send({code: 500, msg: msg});
    });
});

router.post("/admin/auth/payorder/query", (req, resp) => {
    // cacheKey
    let cond = {};
    if(req.body.uid){
        cond.uid = req.body.uid;
    }

    if(req.body.name){
        cond.name = req.body.name;
    }

    let page = 1;
    if(req.body.page){
        page = req.body.page;
    }
    cond.page = page;

    if(req.body.payChannel){
        cond.payChannel = req.body.payChannel;
    }

    if(req.body.status !== undefined && req.body.status !== null){
        cond.status = req.body.statu;
    }

    payOrderService.queryPayOrder(cond).then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        console.logw("getOnlineUserCnt err:", err.message);
        let msg = "系统异常, 请稍后再试";
        if (err instanceof BusiError){
            msg = err.message;
        }

        resp.send({code: 500, msg: msg});
    });
});